from django.template import loader
from django.conf import settings
import os

from goods.models import GoodsChannel, GoodsCategory
from contents.models import Content, ContentCategory


def generate_static_index_html():
    # =======频道分组===========
    categories = {}
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    
    for channel in channels:
        if channel.group_id not in categories:
            categories[channel.group_id] = {
                'channels': [],
                'sub_cats': []
            }

        # 一级分类
        # cat1s = GoodsChannel.objects.filter(group_id=channel.group_id)
        cat1 = channel.category

        categories[channel.group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })

        # 二级分类
        cat2s = GoodsCategory.objects.filter(parent_id=cat1.id)
        for cat2 in cat2s:
            # 三级分类
            cat3s = GoodsCategory.objects.filter(parent_id=cat2.id)
            cat3s_list = []
            for cat3 in cat3s:
                cat3s_list.append({
                    'id': cat3.id,
                    'name': cat3.name
                })
            categories[channel.group_id]['sub_cats'].append({
                'id': cat2.id,
                'name': cat2.name,
                'sub_cats': cat3s_list
            })

        # =====================生成首页广告部分数据=======================
        # 我们定义一个字典, 里面将要存储广告内容部分:
        contents = {}
        # 从 ContentCategory 模型类中获取所有数据, 存放到 content_categories 中:
        content_categories = ContentCategory.objects.all()
        # 遍历刚刚获取的所有数据: 拿到每一个广告分类 cat:
        for cat in content_categories:
            # 根据广告分类的 外键反向
            # 获取广告内容中状态为 True 并且按 sequence 排序的部分,
            # 赋值给上面定义的字典, 快捷键(cat.key) 作为 key, 排序的部分作为value
            contents[cat.key] = Content.objects.filter(category=cat, status=True).order_by('sequence')

        # 第二部分: 模板渲染部分:
        # 把上面两部分获取的有序字典和字典作为变量,拼接新的字典 context
        context = {'categories': categories, 'contents': contents}

        # =====================获取模板,把数据添加进去生成页面====================
        template = loader.get_template('index.html')
        html_text = template.render(context)

        # file_path = settings.GENERATED_STATIC_HTML_FILES_DIR + '/index.html'
        file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')

        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(html_text)

